package com.company.cloud.art.modules.app.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.cloud.art.modules.api.request.ArtistBindUserReq;
import com.company.cloud.art.modules.api.request.ArtistQueryReq;
import com.company.cloud.art.modules.api.response.Artist;
import com.company.cloud.art.modules.api.response.ArtistQueryResp;
import com.company.cloud.art.modules.app.controller.req.ArtistGetParam;
import com.company.cloud.art.modules.app.controller.req.ArtistListParam;
import com.company.cloud.art.modules.base.entity.ArtistInfo;
import com.company.cloud.art.modules.base.service.ArtistInfoService;
import com.company.cloud.art.modules.cache.models.ArtistGroupModel;
import com.company.cloud.art.modules.cache.utils.ArtConvertUtils;
import com.company.cloud.art.modules.mgr.service.ActArtistMgrService;
import com.company.cloud.behavior.modules.api.response.BehaviorSearchListParam;
import com.company.cloud.behavior.modules.api.response.FollowSearchModel;
import com.company.cloud.behavior.modules.api.service.BehaviorClientService;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.auth.annotation.StaffLogc;
import com.company.cloud.common.bean.BaseClientResult;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseConstant;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.CheckUtils;
import com.company.common.server.constant.IRelBusiType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.apache.catalina.LifecycleState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/app/art/artist")
@Api(tags = "ART_保姆")
public class ArtistController {

    @Autowired
    private ActArtistMgrService actArtistMgrService;
    @Autowired
    private ArtistInfoService artistInfoService;
    @Autowired
    private BehaviorClientService behaviorClientService;

    @PostMapping("/bind/user")
    @ApiOperation(value = "艺术家绑定用户", response = String.class)
    @StaffLogc(title = "艺术家绑定用户", action = "艺术家绑定用户", actionAdo = "艺术家")
    public BaseResult query(@RequestBody ArtistBindUserReq params) {
        ArtistInfo artistInfo = artistInfoService.getOne(new QueryWrapper<ArtistInfo>()
                .eq("rows_state", BaseConstant.EnabledEnum.ENABLED.getCode())
                .eq("artist_no", params.getArtistNo())
        );

        if (artistInfo == null) {
            throw new BusinessException("该艺术家不存在");
        }

        if (artistInfo.getUserId() != 0) {
            throw new BusinessException("该艺术家已被用户绑定，请勿重复绑定");
        }

        artistInfo.setUserId(params.getUserId());
        boolean flag = artistInfoService.updateById(artistInfo);
        if (!flag) {
            throw new BusinessException("艺术家绑定失败");
        }

        BaseResult result = BaseResult.ok(params.getArtistNo());
        result.setMsg("艺术家绑定成功");
        return result;
    }

    @PostMapping("/query")
    @ApiOperation(value = "查询", response = Artist.class)
    public BaseResult query(@RequestBody ArtistQueryReq params) {
        ArtistQueryResp data = actArtistMgrService.artistQuery(params);
        return BaseResult.ok(data);
    }

    @PostMapping("/list")
    @ApiOperation(value = "列表(不分页)", response = ArtistGroupModel.class)
    public BaseResult list(@RequestBody ArtistListParam params) {
        List<ArtistInfo> artistList = artistInfoService.list(new QueryWrapper<ArtistInfo>()
                .eq("rows_state", BaseConstant.EnabledEnum.ENABLED.getCode())
                .orderByDesc("orders")
        );
        if (CollectionUtils.isEmpty(artistList)) {
            return BaseResult.ok();
        }
        Map<String, List<Artist>> artistMap = new HashMap<String, List<Artist>>();
        artistList.forEach(item -> {
            Artist artist = ArtConvertUtils.getArtist(item);
            if (StringUtils.isEmpty(params.getNameFirstPy())
                    || params.getNameFirstPy().equals(artist.getNameFirstPy())) {
                List<Artist> _artistList = artistMap.get(artist.getNameFirstPy());
                if (_artistList == null) {
                    _artistList = new ArrayList<Artist>();
                    artistMap.put(artist.getNameFirstPy(), _artistList);
                }
                _artistList.add(artist);
            }
        });

        List<ArtistGroupModel> data = new ArrayList<ArtistGroupModel>();
        for (String key : artistMap.keySet()) {
            data.add(new ArtistGroupModel(key, artistMap.get(key)));
        }
        //根据姓名首字母排序
        Collections.sort(data, new Comparator<ArtistGroupModel>() {
            public int compare(ArtistGroupModel o1, ArtistGroupModel o2) {
                return o1.getNameFirstPy().compareToIgnoreCase(o2.getNameFirstPy());
            }
        });
        return BaseResult.ok(data);
    }


    @GetMapping("/get")
    @ApiOperation(value = "信息", response = Artist.class)
    public BaseResult get(@RequestParam("artistNo") String artistNo) {
        Artist data = actArtistMgrService.artistInfo(artistNo);
        return BaseResult.ok(data);
    }

    @PostMapping("/gets")
    @ApiOperation(value = "多个信息", response = Artist.class)
    public BaseResult gets(@RequestBody ArtistGetParam params) {
        ValidatorUtils.validate(params);
        List<ArtistInfo> artistList = artistInfoService.list(new QueryWrapper<ArtistInfo>()
                .in("artist_no", params.getArtistNos())
                .eq("rows_state", BaseConstant.EnabledEnum.ENABLED.getCode())
                .orderByDesc("orders")
        );
//        List<ArtistInfo> artistList = artistInfoService.listByIds(params.getArtistNos());
        if (CollectionUtils.isEmpty(artistList)) {
            return BaseResult.ok();
        }

        LoginSimpleUserInfo userInfo = AuthContextUtils.getUserNoValidate();
        List<Artist> data = new ArrayList<Artist>();
        List<String> objNos = new ArrayList<>();
        artistList.forEach(item -> {
            objNos.add(item.getArtistNo());
            data.add(ArtConvertUtils.getArtist(item));
        });

        BehaviorSearchListParam behaviorParam = new BehaviorSearchListParam();
        behaviorParam.setUserId(userInfo == null ? null : userInfo.getId());
        behaviorParam.setObjType(IRelBusiType.PTY_Artist_ObjType);
        behaviorParam.setObjNo(objNos);
        BaseClientResult<Map<String, FollowSearchModel>> followData = behaviorClientService.getFollowMap(behaviorParam);

        Map<String, FollowSearchModel> followMap = BaseClientResult.getResultData(followData);
        if (!CollectionUtils.isEmpty(followMap)) {
            data.forEach(item -> {
                FollowSearchModel fsm = followMap.get(item.getArtistNo());
                if (fsm != null) {
                    item.setFollowNum(fsm.getCount());
                    item.setIsFollowed(fsm.getIsFollowed());
                }
            });
        }
        return BaseResult.ok(data);
    }


}
